# -*- coding: utf-8 -*-
# (c) 2015 Mikel Arregi - AvanzOSC
# (c) 2015 Oihane Crucelaegui - AvanzOSC
# License AGPL-3 - See http://www.gnu.org/licenses/agpl-3.0.html

from odoo import _, api, exceptions, fields, models
import odoo.addons.decimal_precision as dp
from odoo.tools.float_utils import float_compare


class masssplitmoves(models.TransientModel):
    _name = 'mass.split.moves'

    @api.multi
    @api.constrains('moves_lines')
    def check_qty(self):
        precision_digits = self.env[
            'decimal.precision'].precision_get('Product Unit of Measure')
        move = self.env['stock.move'].browse(self.env.context['active_id'])
        for record in self.filtered('moves_lines'):
            if float_compare(record.lines_qty, move.product_qty,
                             precision_digits=precision_digits) > 0:
                raise exceptions.UserError(
                    _(u'明细数量不得大于原始需求数！'))

    @api.depends('moves_lines', 'moves_lines.qty')
    def _compute_qties(self):
        move = self.env['stock.move'].browse(self.env.context['active_id'])

        lines_qty = sum(quant_line.qty for quant_line in self.moves_lines)
        self.lines_qty = lines_qty
        self.move_qty = move.product_qty - lines_qty

    name = fields.Char(string=u'名称')
    product_id=fields.Many2one('product.product',u'产品')
    location_id=fields.Many2one('stock.location',u'初始入库位')
    product_qty=fields.Float(u'初始数量')
    lines_qty = fields.Float(
        string=u'分配数', compute='_compute_qties',
        digits=dp.get_precision('Product Unit of Measure'))
    move_qty = fields.Float(string=u'剩余数', compute='_compute_qties',
                            digits=dp.get_precision('Product Unit of Measure'))
    moves_lines = fields.One2many('mass.split.moves.lines',
                                   'mass_wizard', string=u'拆分的明细')

    @api.multi
    def mass_moves(self):
        move = self.env['stock.move'].browse(self.env.context['active_id'])
        moves = []
        if move.picking_id:  # pragma: no cover
            move.picking_id.recompute_pack_op = True
        for quant_id in move.reserved_quant_ids.ids:
            move.write({'reserved_quant_ids': [[3, quant_id]]})
        # 拆分
        move.product_uom_qty=self.move_qty
        for line in self.moves_lines:
            new_move = move.copy({
                'origin': move.origin or move.picking_id.name or "/",
                'product_id': move.product_id.id,
                'product_uom_qty': line.qty,
                'location_id': move.location_id.id,
                'location_dest_id': line.location_id.id,
                'date': move.date,
                'date_expected': move.date_expected,
                'company_id': move.company_id.id,
                'picking_id': move.picking_id.id,
                'picking_type_id': move.picking_type_id.id,
                'propagate': move.propagate,
                'push_rule_id': move.push_rule_id.id,
                'warehouse_id': move.warehouse_id.id,
                'procurement_id': move.procurement_id.id,
            })
            new_move.action_confirm()
        return {}

    @api.model
    def default_get(self, fields):
        res = super(masssplitmoves, self).default_get(fields)
        move = self.env['stock.move'].browse(self.env.context['active_id'])
        res.update({'product_id': move.product_id.id,'location_id': move.location_id.id,'product_qty': move.product_qty})
        res = self._convert_to_write(self._convert_to_cache(res))
        return res


class masssplitmovesLines(models.TransientModel):
    _name = 'mass.split.moves.lines'
    _rec_name = 'mass_wizard'

    mass_wizard = fields.Many2one(
        comodel_name='mass.split.moves', string='Move', required=True,
        ondelete='cascade')
    location_id = fields.Many2one(comodel_name='stock.location', string=u'入库库位')
    qty = fields.Float(
        string=u'数量', digits=dp.get_precision('Product Unit of Measure'))
